import axios from "axios";
import React, { useEffect, useState, useRef } from "react";
import { connect } from "react-redux";
import { PlusOutlined } from "@ant-design/icons";
import {
  Card,
  Button,
  Table,
  Switch,
  Image,
  message,
  Form,
  Modal,
  Input,
  Select,
  Popconfirm,
} from "antd";

import PictureWall from "../product/picture_wall";

const { Option } = Select;

const Slides = (props) => {
  const { userInfo } = props;
  let [slideList, setSlideList] = useState([]);
  let [isLoading, setIsLoading] = useState(true);

  const [form] = Form.useForm();
  let [isModalVisible, setIsModalVisible] = useState(false);
  let [id, setId] = useState("");
  let [operationType, setOperationType] = useState("add");
  const pictureRef = useRef();

  const reqSlideList = async () => {
    const responce = await axios.get(
      "http://api.shop.eduwork.cn/api/admin/slides",
      {
        headers: {
          Authorization: userInfo.token,
        },
      }
    );
    setIsLoading(false);
    setSlideList(responce.data.data);
  };

  const updateStatus = async (id) => {
    const responce = await axios.patch(
      `http://api.shop.eduwork.cn/api/admin/slides/${id}/status`,

      {},
      {
        headers: {
          Authorization: userInfo.token,
        },
      }
    );

    if (responce.status === 204) {
      message.success("商品状态更新成功");
    } else {
      message.error("商品状态更新失败");
    }
  };

  useEffect(() => {
    reqSlideList();
    // eslint-disable-next-line
  }, []);

  const handleCancel = () => {
    form.resetFields();
    setIsModalVisible(false);
  };

  const reqAddSlide = async (values) => {
    try {
      const responce = await axios.post(
        "http://api.shop.eduwork.cn/api/admin/slides",
        values,

        {
          headers: {
            Authorization: userInfo.token,
          },
        }
      );

      if (responce.status === 201) {
        message.success("添加轮播图片成功");
      }

      form.resetFields();
      setIsModalVisible(false);
    } catch (err) {
      message.error("请求参数出错");
    }
  };

  const reqUpdateSlide = async (values) => {
    try {
      const responce = await axios.put(
        `http://api.shop.eduwork.cn/api/admin/slides/${id}`,
        values,

        {
          headers: {
            Authorization: userInfo.token,
          },
        }
      );

      if (responce.status === 204) {
        message.success("更新轮播图片成功");
      }

      form.resetFields();
      setIsModalVisible(false);
    } catch (err) {
      console.log(err);
      message.error("暂无权限更改");
    }
  };

  const reqDeleteSlide = async (item) => {
    try {
      const responce = await axios.delete(
        `http://api.shop.eduwork.cn/api/admin/slides/${item.id}`,

        {
          headers: {
            Authorization: userInfo.token,
          },
        }
      );

      if (responce.status === 204) {
        message.success("删除轮播图片成功");
      }

      form.resetFields();
      setIsModalVisible(false);
    } catch (err) {
      console.log(err);
      message.error("暂无权限删除");
    }
    reqSlideList();
  };

  const toUpdate = (item) => {
    setId(item.id);
    setIsModalVisible(true);
    setOperationType("update");

    form.setFieldsValue({
      title: item.title,
      url: item.url,
      status: item.status,
    });
    const file = { url: item.img_url, key: item.img };
    const fileList = [file];
    pictureRef.current.handleChange({ fileList });
  };

  const toAdd = () => {
    setIsModalVisible(true);
    setOperationType("add");
  };

  const onFinish = async (values) => {
    values.img = values.img[0].key;

    console.log(values);
    if (operationType === "add") {
      reqAddSlide(values);
      reqSlideList();
    } else {
      reqUpdateSlide(values);
    }
  };

  // 删除轮播图popconfirm
  const text = "是否确认删除此轮播图？";

  const columns = [
    {
      title: "轮播图片",
      dataIndex: "img_url",
      width: "15%",
      key: "img_url",
      render: (img_url) => {
        return <Image width={100} src={img_url} />;
      },
    },
    {
      title: "图片名称",
      dataIndex: "title",
      key: "title",
    },

    {
      title: "跳转链接",
      width: "20%",
      dataIndex: "url",
      key: "url",
    },
    {
      title: "是否禁用",
      width: "15%",
      align: "center",
      // dataIndex: "is_on",
      key: "is_on",
      render: (item) => {
        return (
          <Switch
            checkedChildren="启用"
            unCheckedChildren="禁用"
            defaultChecked={item.status === 1 ? true : false}
            onChange={() => {
              updateStatus(item.id);
            }}
          />
        );
      },
    },
    {
      title: "排序",
      width: "10%",
      align: "center",
      dataIndex: "seq",
      key: "seq",
    },
    {
      title: "更新时间",
      width: "15%",
      align: "center",
      dataIndex: "updated_at",
      key: "updated_at",
    },

    {
      align: "center",
      title: "操作",
      width: "15%",
      //dataIndex: "operation",
      key: "operation",
      render: (item) => {
        return (
          <div>
            <Button
              type="link"
              onClick={() => {
                toUpdate(item);
              }}
            >
              编辑
            </Button>
            <br />
            <Popconfirm
              placement="left"
              title={text}
              onConfirm={() => {
                reqDeleteSlide(item);
              }}
              okText="确认"
              cancelText="取消"
            >
              <Button type="link">删除</Button>{" "}
            </Popconfirm>
          </div>
        );
      },
    },
  ];

  const formItemLayout = {
    labelCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 4,
      },
    },
    wrapperCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 16,
      },
    },
  };
  return (
    <div>
      <Card
        extra={
          <Button type="primary" onClick={toAdd}>
            <PlusOutlined />
            新建
          </Button>
        }
      >
        <Table
          dataSource={slideList}
          columns={columns}
          loading={isLoading}
          rowKey={"id"}
          pagination={{
            pageSize: 5,
          }}
          //scroll={{ scrollToFirstRowOnChange: true, y: 350 }}
        />
      </Card>

      <Modal
        title={operationType === "add" ? "新增轮播图" : "修改轮播图"}
        visible={isModalVisible}
        onCancel={handleCancel}
        footer={null}
      >
        <Form
          form={form}
          name="addUser"
          {...formItemLayout}
          onFinish={onFinish}
        >
          <Form.Item
            name="title"
            label="图片名称"
            rules={[
              {
                required: true,
                message: "Please input your username!",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="img"
            label="轮播图片"
            rules={[
              {
                required: true,
                message: "Please input product pic!",
              },
            ]}
          >
            <PictureWall ref={pictureRef}></PictureWall>
          </Form.Item>

          <Form.Item name="url" label="跳转链接">
            <Input />
          </Form.Item>

          <Form.Item name="status" label="是否启用">
            <Select placeholder="select status">
              <Option key={1} value={1}>
                启用
              </Option>
              <Option key={0} value={0}>
                禁用
              </Option>
            </Select>
          </Form.Item>

          <Form.Item
            wrapperCol={{
              span: 12,
              offset: 4,
            }}
          >
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default connect((state) => ({ userInfo: state.userInfo }))(Slides);
